package 邮件知识;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.*;
import javax.mail.internet.*;
import java.io.File;
import java.util.Arrays;
import java.util.List;
import java.util.Properties;

public class MultiAttachmentMailSender {

    public static void main(String[] args) {
        // 邮箱服务器信息
        String host = "mail.xx.com"; // 邮件服务器的地址
        String port = "25"; // 邮件服务器的端口号（例如：25是常用的SMTP端口）

        String username = "xx"; // 发件人邮箱
        String password = "xx"; // 授权码或邮箱密码

        // 邮件信息
        String from = "xx@xx.com"; // 发件人邮箱
        List<String> toList = Arrays.asList("xx@qq.com");
        String subject = "测试多附件邮件";
        String content = "这是一个带多个附件的邮件示例";

        // 附件列表
        List<File> attachments = Arrays.asList(
                new File("restored.jpg")
        );

        // 配置SMTP属性
        Properties props = new Properties();
        props.put("mail.smtp.host", host);
        props.put("mail.smtp.port", port);
        props.put("mail.smtp.auth", "true");
        // props.put("mail.smtp.starttls.enable", "true"); // 启用TLS
        props.put("mail.debug", "true"); // 打开debug调试信息

        Session session = Session.getInstance(props, new Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(username, password);
            }
        });

        try {
            MimeMessage message = new MimeMessage(session);
            message.setFrom(new InternetAddress(from));

            // 添加多个收件人
            for (String to : toList) {
                message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
            }

            message.setSubject(subject);

            // 创建正文部分
            MimeBodyPart textPart = new MimeBodyPart();
            textPart.setText(content, "UTF-8");

            // 创建多部分邮件（正文 + 附件）
            Multipart multipart = new MimeMultipart();
            multipart.addBodyPart(textPart);

            // 添加附件部分
            for (File file : attachments) {
                if (file.exists()) {
                    MimeBodyPart attachPart = new MimeBodyPart();
                    FileDataSource source = new FileDataSource(file);
                    attachPart.setDataHandler(new DataHandler(source));
                    attachPart.setFileName(MimeUtility.encodeText(file.getName(), "UTF-8", null));
                    multipart.addBodyPart(attachPart);
                } else {
                    System.err.println("附件文件不存在: " + file.getAbsolutePath());
                }
            }

            message.setContent(multipart);
            Transport.send(message);

            System.out.println("多附件邮件发送成功！");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

